<template>
  <p class="mb-2">发布新商品</p>
  <div class="w-full bg-white p-4 box-border ">
    <!-- 提示信息 -->
    <el-alert type="info" :closable="false"
      title="发布须知：准确选择类目有利于商品曝光，促进转化；若错放类目将会导致流量降权或下架整改、其他违规处理。查看发布攻略。"></el-alert>

    <!-- 最近使用的分类 -->
    <div class="my-4">
      <div class="font-bold mb-2">最近使用的分类</div>
      <div class="flex flex-wrap gap-2">
        <el-tag v-for="tag in recentCategories" :key="tag.id" closable @close="handleClose(tag)">
          {{ tag.name }}
        </el-tag>
        <button class="text-blue-500 text-sm" @click="clearRecent">清空</button>
      </div>
    </div>
    <!-- 选择分类 -->
    <div class="mt-2">
      <h3 class="text-[15px] mb-4">选择分类</h3>
      <div class="search-box">
        <el-input v-model="searchKeyword" placeholder="请输入关键词搜索分类" :prefix-icon="Search" @input="handleSearch"
          class="mb-4"></el-input>
      </div>

      <div class="flex flex-row ">
        <div class=" border border-gray-200 rounded-r  max-h-100 overflow-y-auto w-64 text-center">
          <ul class="divide-y divide-gray-100">
            <li v-for="category in mainCategories" :key="category.value" @click="selectMainCategory(category)"
              class=" py-2 cursor-pointer hover:bg-gray-50">
              <i :class="category.icon" class="mr-2"></i>
              <el-icon>
                <CircleCheck />
              </el-icon>
              {{ category.label }}
            </li>
          </ul>
        </div>
        <div class=" flex-1 border border-gray-200  ">
          <div v-if="selectedMainCategory">
            <ul class="divide-y divide-gray-100">
              <li v-for="subcategory in selectedMainCategory.subcategories" :key="subcategory.value"
                @click="selectSecondSubCategory(subcategory)" class="px-3 py-2 cursor-pointer hover:bg-gray-50">
                <div class="flex  items-center justify-between">
                  <span>{{ subcategory.label }}</span>
                  <span>&gt;</span>
                </div>
              </li>
            </ul>
          </div>
          <div v-else class="p-4 text-center text-gray-400">
            请先选择一个主分类
          </div>
        </div>
        <div class="flex-1 border border-gray-200  overflow-hidden">
        </div>
      </div>

    </div>

    <div class="mt-4 bg-gray-100 p-4 rounded-sm">
      <span>已选分类：</span>
      <span>{{ selectedPath }}</span>
    </div>
  </div>
  <!-- 基本信息 -->
  <div class="px-4">
    <!-- 基本信息标题 -->
    <div class="text-lg font-semibold mb-4">1 基本信息</div>

    <el-form label-width="100px">
      <el-form-item label="商品轮播图">
        <div class="flex flex-col">
          <span class=" text-gray-500">图片要求：宽高比例为1:1或3:4,且宽高均大于480px,大小3M内。已上传5/10张,拖拽可调整顺序</span>

          <el-upload v-model:file-list="imagesList" action="#" :auto-upload="false" list-type="picture-card" multiple
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-change="handleMainImageChange">
            <!-- <el-icon>
              <Plus />
            </el-icon> -->
            <template #trigger>
              <div class="flex flex-col items-center space-y-2">
                <el-button style="width: 100%;">本地上传</el-button>
                <el-button style="width: 100%; margin: 0;">图片空间上传</el-button>
              </div>
            </template>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
      </el-form-item>

      <el-form-item label="商品标题">
        <el-input placeholder="请输入商品标题"></el-input>
      </el-form-item>
      <el-form-item label="商品属性">
        <div class="bg-gray-100 px-2 w-full">
          <div class="border-b border-gray-300 text-gray-400 py-2 px-4 flex justify-between">
            <span class="flex items-center">填写率<a class="text-green-500">100%</a><i
                class="text-green-500 iconfont icon-yuanhuan ml-1 font-bold "></i></span>
            <span>准确填写属性，有利于商品在搜索和推荐中露出，错误填写可能面临商品下架或流量损失</span>
            <span>没有合适属性值?点击反馈</span>
          </div>
          <!-- <div class="flex  items-center justify-between p-2 "> -->
          <div class="grid grid-cols-2 gap-4  mt-4 p-4">
            <div class="w-full" v-for="(item,index) in productAttrs">
              <div class=" flex items-center">
                <label class="w-30 ">
                  <span class="text-orange-500 pr-2" v-show="item.isImportant">重要</span>
                  {{ item.name }}
                </label>
                <!-- <el-input :placeholder="`请输入${item.name}`" v-model="form.items[index].value"
                  style="width: 70%;"></el-input> -->
                <el-select v-model="form.items[index].value" :placeholder="`请输入${item.name}`" size="large"
                  style="width: 70%" :multiple="item.isMultiple">
                  <el-option v-for="attr in item.values " :key="attr" :label="attr" :value="attr" />
                </el-select>

              </div>
              <p class="ml-31 text-gray-400" v-if="item.comment">{{item.comment}}</p>
            </div>
          </div>
          <!-- <div class="flex  items-center justify-between p-2 ">
            <div class="w-full flex items-center">
              <label class="w-12">后跟</label>
              <el-input placeholder="请输入品牌" style="width: 300px;"></el-input>
            </div>
            <div class="w-full">
              <div class=" flex items-center">
                <label class="w-30 "><span class="text-orange-500 pr-2">重要</span>鞋底材质</label>
                <el-input placeholder="请输入品牌" style="width: 300px;"></el-input>
              </div>
              <p class="ml-30 text-gray-400">该材质必须占鞋底材质30%以上</p>
            </div>
          </div> -->
        </div>
      </el-form-item>
      <el-form-item label="商品视频">
        <div class="flex flex-col">
          <span class=" text-gray-500">视频要求：时长60秒以内：宽高比为1:1或16:9或3:4.上传后展示在商品轮播图位置守卫。享全栈流量扶持，提升转化</span>
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <el-icon>
              <VideoPlay />
            </el-icon>
          </el-upload>
        </div>

      </el-form-item>
      <el-form-item label="商品详情">
        <div class="flex flex-col w-full">
          <span class=" text-gray-500">详情介绍商品以提升转化。若未编辑，商品发布后轮播图将自动填充值图文详情</span>
          <div class=" flex gap-4">
            <div class="border-1 border-gray-300 p-4 rounded-md">
              <span class=" text-gray-500">页面预览</span>
            </div>
            <div class="flex-1 border-1 border-gray-300 p-4 rounded-md">
              <span class=" text-gray-500">快捷编辑</span>
            </div>
          </div>
        </div>
      </el-form-item>
      <div class="text-lg font-semibold mb-4">2 规格与库存</div>
      <el-form-item label="商品规格">
        <div class="bg-gray-100 w-full p-4">
          <!-- 颜色分类 -->
          <div class="mb-2">
            <label class=" mr-2">颜色分类</label>
            <span class=" text-gray-500">选择标准颜色可以增加搜索/导购机会，标准颜色还可以填写颜色备注信息(偏深、偏亮等)</span>
            <div class="flex">
              <el-input placeholder="选择或者输入主色"></el-input>
              <el-input placeholder="备注(偏深/偏浅)"></el-input>
            </div>

          </div>
          <!-- 鞋码 -->
          <div class="p-2 bg-white">
            <div class="flex items-center justify-between border-b-1 border-gray-300 p-2">
              <div class=" flex items-center  gap-4  ">
                <span class="  whitespace-nowrap">鞋码</span>
                <el-select placeholder="请选择" style="width: 200px;" size="small">
                </el-select>
                <span class=" whitespace-nowrap text-gray-500">可从尺码模版选择尺码</span>
              </div>
              <span class="text-blue-400 px-4"> 全部尺码表</span>

            </div>
            <div class="flex items-center gap-4 mt-2 p-2">
              <div class="mr-2  border border-gray-300 divide-x divide-gray-300">
                <span class="p-1">欧码</span>
                <span class="p-1">英码</span>
                <span class="p-1">美码</span>
              </div>
              <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                全选以下规格值
              </el-checkbox>
            </div>
            <!-- 鞋码展示区域 -->
            <div class="p-2">
              <el-checkbox-group v-model="checkedSize" @change="handleCheckedSizeChange">
                <div class="grid grid-cols-4 gap-2">
                  <el-checkbox v-for="size in shoeSize[0].values" :key="size" :label="size" :value="size">
                    {{ size }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>

          </div>

        </div>

      </el-form-item>
      <el-form-item label="价格及库存">
        <div class="bg-gray-100 w-full p-4">
          <span class="text-orange-400">请入如实填写库存信息，以保证商品可以在承诺发货时间内发货，避免物流违规</span>
          <el-table :data="priceAndStockData" header-row-class-name="orange-header" border
            :span-method="objectSpanMethod" class="stock-table">
            <el-table-column fixed label="颜色分类" prop="color" />
            <el-table-column label="鞋码" prop="size" />
            <el-table-column label="当前库存" prop="oldStock" />
            <el-table-column label="库存增减" width="200">
              <template #default="scope">
                <div class="flex items-center ">
                  <button class="border-y border-l p-1 rounded-l border-gray-400">增</button>
                  <button class="border p-1 rounded-r border-gray-400">减</button>
                  <el-input v-model="scope.row.stock" placeholder="请输入" class="ml-1">
                  </el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="改后库存">
              <template #default="scope">
                <el-input v-model="scope.row.newStock" placeholder="请输入">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="发布价(元)" prop="publishPrice" />
            <el-table-column label="现价(元)" prop="nowPrice" />
            <el-table-column label="预览图">
              <template #default="scope">
                <img :src="scope.row.image" style="width: 50px; height: 50px;" />
              </template>
            </el-table-column>
            <el-table-column label="规格编码" prop="specCode">
            </el-table-column>
            <el-table-column label="状态" fixed="right">
              <template #default="scope">
                <span v-if="scope.row.status === '1'">已上架</span>
                <span v-else>未上架</span>
                <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                  @change="handleSwitchChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item>
        <div class=" text-center w-full">
          <el-affix position="bottom" :offset="20">

            <el-button type="primary">提交</el-button>
            <el-button>保存草稿</el-button>

          </el-affix>
        </div>
      </el-form-item>
    </el-form>
  </div>


</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { Search, Plus, VideoPlay } from '@element-plus/icons-vue';
const mainCategories=  ref( [
  { value: 'man', label: '男鞋',  },
  { value: 'woman', label: '女鞋', },
  { value: 'child', label: '童鞋',  },
])
const selectedMainCategory=ref(null);
// 选中的分类
const selectedCategory = ref(null);
// 当前选择的路径
const selectedPath = ref('');
// 最近使用的分类
const recentCategories = ref([
  { id: 111, name: '女鞋 > 低帮鞋 > 老妈鞋' },
  { id: 112, name: '女鞋 > 低帮鞋 > 板鞋' },
  { id: 113, name: '女鞋 > 低帮鞋 > 运动休闲鞋' },
  { id: 114, name: '女鞋 > 拖鞋 > 一字拖' },
  { id: 115, name: '女鞋 > 拖鞋 > 勃肯鞋/软木鞋' }
]);

// 搜索推荐的关键词
const searchKeyword = ref('');

const selectMainCategory = (category) => {
  selectedMainCategory.value = {
    ...category,
    subcategories: getSubcategories(category.value)
  };
  console.log(category,'<<category>>');
  selectedPath.value = category.label;
}
const getSubcategories = (mainCategory) => {
  // 模拟获取子分类数据
  const subcategories = {
    woman: [
      { value: 'shoes', label: '低帮鞋' },
      { value: 'sneakers', label: '板鞋' },
      { value: 'sandals', label: '凉鞋' }
    ],
    man: [
      { value: 'sport', label: '运动鞋' },
      { value: 'sandals', label: '凉鞋' }
    ],
    child: [
      { value: 'sport', label: '运动鞋' },
      { value: 'sandals', label: '凉鞋' }
    ]
  };

  return subcategories[mainCategory] || [];
}
// 右侧分类选择处理
const selectSecondSubCategory = (subCategory) => {
  if(selectedPath.value.indexOf('>')===-1)
    // 更新路径
    selectedPath.value = `${selectedPath.value} > ${subCategory.label}`;
  else
    selectedPath.value = selectedPath.value.split('>')[0]+'>'+subCategory.label;  
}

// 搜索结果处理
const handleSearch = (keyword) => {
  // 实际应用中应该根据关键词从后端获取分类数据
  console.log('搜索关键词:', keyword);
};

// 关闭最近使用的分类标签
const handleClose = (tag) => {
  recentCategories.value = recentCategories.value.filter(item => item.id !== tag.id);
};

// 清空最近使用的分类
const clearRecent = () => {
  recentCategories.value = [];
};
//商品主图
const imagesList=ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview= (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const handleMainImageChange  = (file, fileList) => {
  //获取图片
  console.log(file, fileList)
}

//商品属性
const  productAttrs = ref([
  {
    name: '品牌',
    values: ['红丽', '蓝宝', ],
  },
  {
    name: '鞋面材质',
    values: ['超纤皮', '真皮', 'PU', '人造革'],
    isImportant:true,
    comment:'该材质必须占鞋面材质30%以上'
  },
  
  {
    name: '后跟高',
    values: ['5cm-8cm', '3cm-5cm', '8cm-10cm'],
  },
  {
    name: '鞋底材质',
    values: ['发泡橡胶', 'EVA底', '牛筋底'],
    isImportant: true,
    comment: '该材质必须占鞋底材质30%以上'
  },
  {
    name: '闭合方式',
    values: ['系带', '魔术贴', '一字式扣带'],
  },
  {
    name: '风格',
    values: ['韩版', 'EVA底', '牛筋底'],
    isImportant: true,
  },
  {
    name: '上市时间',
    values: ['2025年春季', '2025年春夏季'],
  },
  {
    name: '制作工艺',
    values: ['注塑', '胶粘', '线缝','模压'],
    isImportant: true,
  },
  {
    name: '鞋面内里材质',
    values: ['网面', '超纤皮', '纯真皮'],
    comment: '该材质必须占鞋面内里材质30%以上'
  },
  {
    name: '鞋垫材质',
    values: ['超纤皮', '真皮'],
    comment: '该材质必须占鞋垫材质30%以上'
  },
  {
    name: '鞋头款式',
    values: ['圆头', '尖头', '方头','平头'],
  },
  {
    name: '跟底款式',
    values: ['松糕底', '平底', '高跟'],
    isImportant: true,
  },
  {
    name: '开口深度',
    values: ['中口', 'EVA底', '牛筋底'],
  },
  {
    name: '功能',
    values: ['防滑', '增高', '耐磨'],
    isMultiple:true
  },
  {
    name: '款式',
    values: ['包根跟', '半托'],
  },
    {
    name: '使用季节',
    values: ['不限季节', '春秋', '夏季','冬季'],
  },
  
])
const form  = reactive({
  items: productAttrs.value.map(attr => ({
    name: attr.name,
    value: '',
  })),//商品属性

})
watch(()=>form.items,(newVal,oldVal)=>{ 
  console.log(newVal,'<<<newVal',oldVal,'<<<oldVal');
},{deep:true})


// 鞋码
const  shoeSize = ref([
  {
    name: '欧码',
    values: ['35', '36', '37', '38', '39', '40', '41', '42', '35.5', '36.5', '37.5', '38.5', '39.5', '40.5', '41.5' ]
  },
  {
    name: '中国码',
    values: ['220', '225', '230', '235', '240', '245', '250', '255', '260',  ]
  },
  {
    name: '美码',
    values: ['5', '6', '7', '8', '9', '10', '11', '22', '5H', '6H', '7H', '8H', '9H', '10H', '11H' ]
  },
])
const  checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedSize = ref(['35', '36'])
const handleCheckAllChange = (val) => {
  console.log(shoeSize, 'aaaaa')
  checkedSize.value = val ? shoeSize.value[0].values : []
 
  isIndeterminate.value = false
}
const handleCheckedSizeChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === shoeSize.value[0].values.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < shoeSize.value[0].values.length
}

//价格及库存
const  priceAndStockData = ref([
  {
    color: '米白色',
    size:37,
    oldStock:200,
    newStock:200,
    nowPrice:100,
    publishPrice:100,
    image:'',
    specCode:'高丽鞋业-c-168',
    status:'1'
  },
  {
    color: '米白色',
    size:38,
    oldStock:200,
    newStock:200,
    nowPrice:100,
    publishPrice:100,
    image:'',
    specCode:'高丽鞋业-c-169',
    status:'1'
  }
])

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  // console.log(row, column, rowIndex, columnIndex);
  if (columnIndex === 0) {
    // Find all rows with the same color
    const sameColorRows = priceAndStockData.value.filter(item => item.color === row.color);
    // Find the first occurrence of this color
    const firstIndex = priceAndStockData.value.findIndex(item => item.color === row.color);
    // If this is the first row of this color group
    if (rowIndex === firstIndex) {
      return {
        rowspan: sameColorRows.length,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
}
//开关 上架下架开关
const handleSwitchChange = (row) => {
  console.log(row);
  //todo 调用接口修改上架和下架的状态
}
</script>
<style scoped>

</style>
<style>
/* 表头样式 */
.orange-header th {
  background-color: #eee !important;
  /* 橘色背景 */
  color: #777 !important;
  /*文字颜色*/
}

/* 可选：hover效果 */
.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #ffefd5 !important;
}
</style>